<template>
  <div class="container mx-auto px-4 py-8">
    <!-- 搜索框 -->
    <div class="max-w-2xl mx-auto mb-8">
      <el-input
        v-model="searchKeyword"
        size="large"
        placeholder="搜索电影、电视剧、演员..."
        class="search-input"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button :icon="Search" @click="handleSearch" />
        </template>
      </el-input>

      <!-- 热门搜索 -->
      <div v-if="!searchKeyword && hotSearches.length" class="mt-6">
        <h3 class="text-gray-400 mb-3">热门搜索</h3>
        <div class="flex flex-wrap gap-2">
          <el-tag
            v-for="item in hotSearches"
            :key="item"
            type="info"
            effect="plain"
            class="cursor-pointer hover:opacity-80"
            @click="searchKeyword = item; handleSearch()"
          >
            {{ item }}
          </el-tag>
        </div>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div v-if="hasSearched">
      <!-- 结果统计 -->
      <div class="mb-6">
        <h2 class="text-xl text-gray-400">
          搜索 "<span class="text-white font-semibold">{{ lastSearchKeyword }}</span>"
          找到 <span class="text-primary">{{ total }}</span> 个结果
        </h2>
      </div>

      <!-- 结果列表 -->
      <div v-if="loading" class="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
        <el-skeleton v-for="i in 12" :key="i" :rows="0" animated class="h-80">
          <template #template>
            <el-skeleton-item variant="image" class="w-full h-64" />
            <el-skeleton-item variant="text" class="mt-2" />
            <el-skeleton-item variant="text" style="width: 60%" />
          </template>
        </el-skeleton>
      </div>

      <div v-else-if="searchResults && searchResults.length > 0" class="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
        <MovieCard
          v-for="movie in searchResults"
          :key="movie.movieBasicsId"
          :movie="movie"
        />
      </div>

      <el-empty v-else description="没有找到相关结果">
        <template #description>
          <p class="text-gray-400">试试其他关键词吧</p>
        </template>
      </el-empty>

      <!-- 分页 -->
      <div v-if="total > pageSize" class="mt-8 flex justify-center">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[12, 24, 36, 48]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 推荐内容 -->
    <div v-if="!hasSearched" class="space-y-12">
      <!-- 热门电影 -->
      <section>
        <h2 class="text-2xl font-bold text-white mb-6">热门电影</h2>
        <div class="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
          <MovieCard
            v-for="movie in hotMovies"
            :key="movie.movieBasicsId"
            :movie="movie"
          />
        </div>
      </section>

      <!-- 最新上映 -->
      <section>
        <h2 class="text-2xl font-bold text-white mb-6">最新上映</h2>
        <div class="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
          <MovieCard
            v-for="movie in latestMovies"
            :key="movie.movieBasicsId"
            :movie="movie"
          />
        </div>
      </section>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 搜索相关
const searchKeyword = ref(route.query.keyword as string || '')
const lastSearchKeyword = ref('')
const hasSearched = ref(false)
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(24)
const total = ref(0)
const searchResults = ref<any[]>([])
const hotMovies = ref<any[]>([])
const latestMovies = ref<any[]>([])

// 热门搜索词
const hotSearches = ['复仇者联盟', '流浪地球', '长津湖', '你好李焕英', '唐人街探案', '哪吒', '战狼', '红海行动']

// 执行搜索
const handleSearch = async () => {
  const keyword = searchKeyword.value.trim()
  if (!keyword) return

  loading.value = true
  lastSearchKeyword.value = keyword
  hasSearched.value = true
  currentPage.value = 1

  // 更新URL
  router.push({
    query: { keyword }
  })

  try {
    const data: any = await $fetch('/dev-api/app/movieapp/search', {
      params: {
        keyword,
        pageNum: currentPage.value,
        pageSize: pageSize.value
      }
    })

    // /app/** 接口返回 {rows: [], total: number}
    searchResults.value = data.rows || []
    total.value = data.total || 0
  } catch (error) {
    console.error('搜索失败:', error)
    searchResults.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 获取热门电影
const getHotMovies = async () => {
  try {
    const data: any = await $fetch('/dev-api/app/movieapp/hot', {
      params: {
        pageSize: 12
      }
    })

    // /app/** 接口返回 {rows: [], total: number}
    hotMovies.value = data.rows || []
  } catch (error) {
    console.error('获取热门电影失败:', error)
  }
}

// 获取最新电影
const getLatestMovies = async () => {
  try {
    const data: any = await $fetch('/dev-api/app/movieapp/new', {
      params: {
        pageSize: 12
      }
    })

    // /app/** 接口返回 {rows: [], total: number}
    latestMovies.value = data.rows || []
  } catch (error) {
    console.error('获取最新电影失败:', error)
  }
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  handleSearch()
}

const handlePageChange = (val: number) => {
  currentPage.value = val
  handleSearch()
}

// 监听路由变化
watch(() => route.query.keyword, (newKeyword) => {
  if (newKeyword && newKeyword !== searchKeyword.value) {
    searchKeyword.value = newKeyword as string
    handleSearch()
  }
})

// 初始化
onMounted(async () => {
  if (searchKeyword.value) {
    await handleSearch()
  } else {
    await Promise.all([
      getHotMovies(),
      getLatestMovies()
    ])
  }
})

// SEO设置
useSeoMeta({
  title: searchKeyword.value ? `搜索：${searchKeyword.value}` : '搜索',
  description: '搜索您想观看的影视内容',
})
</script>

<style scoped>
.search-input :deep(.el-input__wrapper) {
  background-color: rgba(31, 41, 55, 0.8);
  border-radius: 9999px;
  padding: 8px 16px;
}

.search-input :deep(.el-input-group__append) {
  background-color: transparent;
  border-radius: 0 9999px 9999px 0;
  border-left: 1px solid rgba(55, 65, 81, 0.5);
}

.search-input :deep(.el-input__inner) {
  color: white;
  font-size: 1.125rem;
}

:deep(.el-pagination) {
  --el-pagination-bg-color: transparent;
  --el-pagination-text-color: rgba(255, 255, 255, 0.8);
  --el-pagination-button-disabled-bg-color: rgba(31, 41, 55, 0.5);
  --el-pagination-button-disabled-color: rgba(255, 255, 255, 0.3);
  --el-pagination-hover-color: #409EFF;
}

:deep(.el-empty__description) {
  color: rgba(255, 255, 255, 0.6);
}

:deep(.el-tag) {
  background-color: rgba(31, 41, 55, 0.8);
  border-color: rgba(55, 65, 81, 0.5);
  color: rgba(255, 255, 255, 0.8);
}
</style>
